import Tooltip from "@/components/Tooltip";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/use-toast";
import useThreadCodeBlock from "@/plugins/__core__/dom-observers/thread/code-blocks/hooks/useThreadCodeBlock";
import { MermaidRendererService } from "@/plugins/thread-artifacts/mermaid-renderer/service/service-init";
import { useArtifactsStore } from "@/plugins/thread-artifacts/store";

import TablerExternalLink from "~icons/tabler/external-link";

export default function MermaidOpenInPlayground() {
  const selectedCodeBlockLocation = useArtifactsStore(
    (store) => store.selection.selectedCodeBlockLocation,
  );

  const selectedCodeBlock = useThreadCodeBlock({
    messageBlockIndex: selectedCodeBlockLocation?.messageBlockIndex,
    codeBlockIndex: selectedCodeBlockLocation?.codeBlockIndex,
  });

  if (!selectedCodeBlock) return null;

  return (
    <Tooltip content={t("plugin-artifacts.tooltip.openInMermaid")}>
      <Button
        variant="ghost"
        size="iconSm"
        onClick={async () => {
          if (!selectedCodeBlock.content.code) return;

          const url = await MermaidRendererService.Instance.getPlaygroundUrl(
            selectedCodeBlock.content.code,
          );

          if (!url) {
            return toast({
              title: t("plugin-artifacts.error.previewUrl"),
            });
          }

          window.open(url, "_blank");
        }}
      >
        <TablerExternalLink className="x:size-4" />
      </Button>
    </Tooltip>
  );
}
